package com.linxianqin.springbootVue.controller.system;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linxianqin.springbootVue.config.SysBootVueConfig;
import com.linxianqin.springbootVue.domain.constant.UserConstants;
import com.linxianqin.springbootVue.domain.convert.SysPostConvert;
import com.linxianqin.springbootVue.domain.convert.SysRoleConvert;
import com.linxianqin.springbootVue.domain.convert.SysUserConvert;
import com.linxianqin.springbootVue.domain.dto.SysRoleDTO;
import com.linxianqin.springbootVue.domain.dto.SysUserDTO;
import com.linxianqin.springbootVue.domain.enums.BusinessType;
import com.linxianqin.springbootVue.domain.model.AjaxResult;
import com.linxianqin.springbootVue.domain.model.LoginUser;
import com.linxianqin.springbootVue.domain.page.TableDataInfo;
import com.linxianqin.springbootVue.domain.query.SysUserQuery;
import com.linxianqin.springbootVue.domain.vo.SysUserExcel;
import com.linxianqin.springbootVue.manage.annotation.SysLog;
import com.linxianqin.springbootVue.manage.core.BaseController;
import com.linxianqin.springbootVue.service.SysPostService;
import com.linxianqin.springbootVue.service.SysRoleService;
import com.linxianqin.springbootVue.service.SysUserService;
import com.linxianqin.springbootVue.service.webService.TokenService;
import com.linxianqin.springbootVue.utils.SecurityUtils;
import com.linxianqin.springbootVue.utils.ServletUtils;
import com.linxianqin.springbootVue.utils.file.FileUploadUtils;
import com.linxianqin.springbootVue.utils.poi.ExcelUtil;
import com.linxianqin.springbootVue.utils.text.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lxq
 * @version 1.0
 * @description: 用户信息
 * @date 2020/12/16 9:10
 */
@Slf4j
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    private final SysUserService userService;
    private final SysRoleService roleService;
    private final SysPostService postService;
    private final TokenService tokenService;
    public SysUserController(SysUserService userService,SysRoleService roleService,
                             SysPostService postService,TokenService tokenService){
        this.userService=userService;
        this.roleService=roleService;
        this.postService=postService;
        this.tokenService=tokenService;
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUserQuery query)
    {
        log.info("查询的信息：{}",query);
        //构建分页bean
        Page<SysUserDTO> page = buildPage();
        //查询分页数据
        Page<SysUserDTO> dtoPage = userService.selectUserDeptPage(page,query);
        return getDataTable(dtoPage);
    }

    /**
     * 下载用户模板
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<SysUserExcel> util = new ExcelUtil<SysUserExcel>(SysUserExcel.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        log.info("测试打印userId:{}",userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRoleDTO> roleDTOList= SysRoleConvert.INSTANCE.entity2dto(roleService.list());
        ajax.put("roles", SysUserDTO.isAdmin(userId) ? roleDTOList : roleDTOList.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", SysPostConvert.INSTANCE.entity2dto(postService.list()));
        if (StringUtils.isNotNull(userId))
        {
            ajax.put(AjaxResult.DATA_TAG, SysUserConvert.INSTANCE.entity2dto(userService.getById(userId)));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @SysLog(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUserDTO userDTO)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(userDTO.getUserName())))
        {
            return AjaxResult.error("新增用户'" + userDTO.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(userDTO.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(userDTO)))
        {
            return AjaxResult.error("新增用户'" + userDTO.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(userDTO.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(userDTO)))
        {
            return AjaxResult.error("新增用户'" + userDTO.getUserName() + "'失败，邮箱账号已存在");
        }
        return toAjax(userService.insertUser(userDTO));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @SysLog(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody  SysUserDTO userDTO)
    {
        userService.checkUserAllowed(userDTO);
        if (StringUtils.isNotEmpty(userDTO.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(userDTO)))
        {
            return AjaxResult.error("修改用户'" + userDTO.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(userDTO.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(userDTO)))
        {
            return AjaxResult.error("修改用户'" + userDTO.getUserName() + "'失败，邮箱账号已存在");
        }
        return toAjax(userService.updateUser(userDTO));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @SysLog(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable List<Long> userIds)
    {
        return toAjax(userService.deleteUserByIds(userIds));
    }


    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @SysLog(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody  SysUserDTO userDTO)
    {
        userService.checkUserAllowed(userDTO);
        userDTO.setPassword(SecurityUtils.encryptPassword(userDTO.getPassword()));
        userDTO.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateById(SysUserConvert.INSTANCE.dto2entity(userDTO)));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @SysLog(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody  SysUserDTO userDTO)
    {
        userService.checkUserAllowed(userDTO);
        userDTO.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateById(SysUserConvert.INSTANCE.dto2entity(userDTO)));
    }

}
